package com.newway.back.controller;

import com.alibaba.fastjson.JSONObject;
import com.newway.LoginUser;
import com.newway.back.security.MyUserDetails;
import com.newway.common.Result;
import com.newway.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/back")
public class LoginController {


    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
     *         System.out.println(bCryptPasswordEncoder.encode("admin"));
     * @param loginUser
     * @return
     */
    @PostMapping("/login")
    public Result<String> login(@RequestBody LoginUser loginUser){
        Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginUser.getUserName(), loginUser.getPassword()));
        MyUserDetails details = (MyUserDetails)authenticate.getPrincipal();
        loginUser.setMyUserDetails(details);
        String token = jwtTokenUtil.createToken(loginUser);
        return Result.success(token);
    }

}
